package com.brainhealth.customer.service.impl;

import com.brainhealth.common.utils.file.FileUploadUtils;
import com.brainhealth.common.utils.file.FileUtils;
import com.brainhealth.customer.config.MinioConfig;
import com.brainhealth.customer.domain.vo.SysFileVO;
import com.brainhealth.customer.service.IMinioService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class MinioServiceImpl implements IMinioService
{
    private static final Logger logger = LoggerFactory.getLogger(MinioServiceImpl.class);

    @Autowired
    private MinioConfig minioConfig;

    @Override
    public List<SysFileVO> uploadFile(MultipartFile[] file, String source)
    {
        List<SysFileVO> lstFiles = new ArrayList<>();
        try
        {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioConfig.getIp())
                    .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                    .build();
            for (MultipartFile multipartFile : file) {
                String fileName = FileUploadUtils.extractFilename(multipartFile);
                PutObjectArgs args = PutObjectArgs.builder()
                        .bucket(minioConfig.getBucketName())
                        .object(source + "/" + fileName)
                        .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                        .contentType(multipartFile.getContentType())
                        .build();
                minioClient.putObject(args);
                String url = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + source + "/" + fileName;
                SysFileVO fileVO = new SysFileVO();
                fileVO.setUrl(url);
                fileVO.setName(FileUtils.getName(url));
                fileVO.setOldName("/" + source + "/" + fileName);
                lstFiles.add(fileVO);
            }
        }catch (Exception e)
        {
            logger.error(e.getMessage());
            return lstFiles;
        }
        return lstFiles;
    }
}
